package com.yz.kronos.schedule.handle;

import com.yz.kronos.schedule.queue.ShareQueue;
import io.fabric8.kubernetes.api.model.batch.Job;
import io.fabric8.kubernetes.client.informers.ResourceEventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author shanchong
 * @date 2021/2/7
 **/
@Slf4j
@Service
public class CallbackResourceEventHandler implements ResourceEventHandler<Job> {

    /**
     * Called when an object is added.
     *
     * @param obj object
     */
    @Override
    public void onAdd(final Job obj) {
        if (obj.getStatus().getConditions().stream().noneMatch(e->"Complete".equals(e.getStatus()))) {
            //添加任务分片队列
            ShareQueue.put(obj.getMetadata().getName(), obj.getSpec().getCompletions());
            log.info("pod haven added obj:{}", obj);
        }
    }

    /**
     * Called when an object is modified. Note that oldObj is the last known state of the object -- it is possible that
     * several changes were combined together, so you can't use this to see every single change. It is also called when
     * a re-list happens, and it will get called even if nothing changes. This is useful for periodically evaluating or
     * syncing something.
     *
     * @param oldObj old object
     * @param newObj new object
     */
    @Override
    public void onUpdate(final Job oldObj, final Job newObj) {
        log.info("pod status changed job={}", newObj);
        String id = newObj.getMetadata().getName();
        if (id == null) {
            return;
        }
        String flowId = id.split("-")[0];
        String index = id.split("-")[1];
        Synchronizer.unlock(flowId, Integer.parseInt(index));
    }

    /**
     * Gets the final state of the item if it is known, otherwise it would get an object of the
     * DeletedFinalStateUnknown. This can happen if the watch is closed and misses the delete event and we don't notice
     * the deletion until the subsequent re-list.
     *
     * @param obj
     * @param deletedFinalStateUnknown
     */
    @Override
    public void onDelete(final Job obj, final boolean deletedFinalStateUnknown) {
        log.warn("pod interrupted job={}", obj);
    }
}
